import base64
import json
import os
from concurrent.futures import ThreadPoolExecutor
from json import JSONDecodeError

import requests

host = "https://www.retone-hearing.fit"
s = requests.Session()
header = {"Content-Type": "application/json"}


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


def login(account, password='cc1234'):
    login_url = '/microServiceUser/responseEncode/requestDecode/login'
    data = {
        "type": 0,
        "sourcePlatform": "RETONE_FIT",
        "password": "cc1234",
        "loginObject": account
    }
    with s.post(host + login_url, headers=header, data=enconde_bs64(data)) as resp:
        print(resp)
        try:
            if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
                print(f'resp.status = {resp.status_code}, resp.text={resp.json()}')
            else:
                with open('cookies.txt', mode='a') as f:

                    f.write(resp.cookies.values()[0] + '\n')
        except JSONDecodeError:
            resp.failure("Response could not be decoded as JSON")
        except KeyError:
            resp.failure("Response did not contain expected key 'data'")

# 打开登录用户名,将所有的用户名写入一个列表
tester_list = []
with open('binduser.txt', mode='r', encoding='utf-8') as f:
    for _ in f:
        tester_list.append(_.strip())


# 打开线程
tasks = set()
with ThreadPoolExecutor(500) as t:
     # tester_list 列表控制登录用户数量
    for username in tester_list:
        # print(username)
        future = t.submit(login, username.strip())

